import { createSlice, PayloadAction } from '@reduxjs/toolkit'

export type ThemeMode = 'light' | 'dark'
export type Language = 'zh' | 'en'

interface AuthState {
  token: string | null
  user: {
    id: number
    username: string
    email: string
    role: string
    avatar?: string
  } | null
}

interface AppState {
  auth: AuthState
  theme: ThemeMode
  language: Language
  loading: boolean
  error: string | null
  sidebarOpen: boolean
}

const initialState: AppState = {
  auth: {
    token: null,
    user: null,
  },
  theme: 'light',
  language: 'zh',
  loading: false,
  error: null,
  sidebarOpen: false
}

const appSlice = createSlice({
  name: 'app',
  initialState,
  reducers: {
    setAuth: (state, action: PayloadAction<AuthState>) => {
      state.auth = action.payload
    },
    setTheme: (state, action: PayloadAction<ThemeMode>) => {
      state.theme = action.payload
    },
    toggleTheme: (state) => {
      state.theme = state.theme === 'light' ? 'dark' : 'light'
    },
    setLanguage: (state, action: PayloadAction<Language>) => {
      state.language = action.payload
    },
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.loading = action.payload
    },
    setError: (state, action: PayloadAction<string | null>) => {
      state.error = action.payload
    },
    logout: (state) => {
      state.auth = initialState.auth
    },
    toggleSidebar: (state) => {
      state.sidebarOpen = !state.sidebarOpen
    },
    setSidebarOpen: (state, action: PayloadAction<boolean>) => {
      state.sidebarOpen = action.payload
    }
  },
})

export const {
  setAuth,
  setTheme,
  toggleTheme,
  setLanguage,
  setLoading,
  setError,
  logout,
  toggleSidebar,
  setSidebarOpen
} = appSlice.actions

export default appSlice.reducer 